<template>
  <view class="app-container" :style="{backgroundColor: '#f5f5f5'}">
    <!-- 搜索区域 -->
    <van-collapse :value="['search']">
      <van-collapse-item title="筛选条件" name="search">
        <van-form @submit="handleQuery">
          <van-field
            v-model="queryParams.applyNo"
            label="申请单号"
            placeholder="请输入申请单号"
            clearable
          />
          <van-field
            v-model="queryParams.applyType"
            is-link
            readonly
            label="申请类型"
            placeholder="请选择"
            @click="showApplyTypePicker = true"
          />
          <!-- 其他搜索字段类似 -->
          
          <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit" color="#4CAF50">
              搜索
            </van-button>
            <van-button 
              round block 
              style="margin-top: 8px;" 
              @click="resetQuery"
              color="#9E9E9E">
              重置
            </van-button>
          </div>
        </van-form>
      </van-collapse-item>
    </van-collapse>

    <!-- 操作按钮 -->
    <view class="action-btns">
      <van-button 
        icon="plus" 
        type="primary" 
        @click="handleAdd"
        color="#4CAF50">
        新增
      </van-button>
      <van-button 
        icon="edit" 
        type="info"
        :disabled="single"
        @click="handleUpdate"
        color="#388E3C">
        修改
      </van-button>
      <van-button 
        icon="delete" 
        type="danger" 
        :disabled="multiple"
        @click="handleDelete"
        color="#D32F2F">
        删除
      </van-button>
    </view>

    <!-- 数据列表 -->
    <scroll-view 
      scroll-y 
      style="height: 60vh;"
      class="data-list">
      <van-checkbox-group v-model="checkedIds">
        <van-cell-group>
          <van-cell
            v-for="item in applyList"
            :key="item.id"
            clickable
            @click="handleItemClick(item)">
            <template #right-icon>
              <van-checkbox :name="item.id" />
            </template>
            <view class="list-item">
              <view class="item-header">
                <text class="item-no">{{ item.applyNo }}</text>
                <van-tag :type="getStatusTagType(item.auditStatus)">
                  {{ formatAuditStatus(item.auditStatus) }}
                </van-tag>
              </view>
              <view class="item-content">
                <text>类型：{{ formatApplyType(item.applyType) }}</text>
                <text>申请人：{{ formatApplyUser(item.applyUser) }}</text>
                <text>申请时间：{{ formatTime(item.applyTime) }}</text>
              </view>
            </view>
          </van-cell>
        </van-cell-group>
      </van-checkbox-group>
    </scroll-view>

    <!-- 分页 -->
    <van-pagination
      v-model="currentPage"
      :total-items="total"
      :items-per-page="queryParams.pageSize"
      @change="handlePageChange"
      color="#4CAF50"
    />

    <!-- 弹窗表单 -->
    <van-popup
      v-model:show="showForm"
      position="bottom"
      round
      :style="{ height: '90%' }">
      <van-form @submit="saveForm">
        <view class="form-header">
          <text class="form-title">{{ formTitle }}</text>
          <van-icon name="close" @click="cancel" />
        </view>

        <scroll-view scroll-y style="height: 75vh;">
          <van-field
            v-model="form.applyNo"
            label="申请单号"
            placeholder="系统自动生成"
            readonly
          />
          
          <van-field
            v-model="form.planNo"
            label="计划单号"
            placeholder="请选择计划"
            readonly
            is-link
            @click="handleSelectPlan"
          />

          <!-- 其他表单字段 -->

          <view class="sub-table">
            <view class="sub-header">
              <text>采购明细</text>
              <van-button 
                size="mini" 
                @click="handleAddDetail"
                color="#4CAF50">
                添加明细
              </van-button>
            </view>
            
            <view 
              v-for="(detail, index) in detailList"
              :key="index"
              class="detail-item">
              <van-field
                v-model="detail.materialName"
                label="物料名称"
                placeholder="请选择物料"
                readonly
                is-link
                @click="handleSelectMaterial(index)"
              />
              <van-field
                v-model="detail.price"
                label="单价"
                type="number"
                placeholder="请输入单价"
              />
              <van-field
                v-model="detail.quantity"
                label="数量"
                type="number"
                placeholder="请输入数量"
              />
            </view>
          </view>
        </scroll-view>

        <view class="form-actions">
          <van-button 
            round 
            block 
            type="primary" 
            native-type="submit"
            color="#4CAF50">
            保存
          </van-button>
          <van-button 
            round 
            block 
            style="margin-top: 8px;" 
            @click="cancel"
            color="#9E9E9E">
            取消
          </van-button>
        </view>
      </van-form>
    </van-popup>

    <!-- 选择器弹窗 -->
    <van-popup v-model:show="showPlanSelect" position="bottom">
      <plan-selector @confirm="handlePlanSelect" @cancel="showPlanSelect = false" />
    </van-popup>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';

// 模拟数据
const mockData = {
  applyList: [],
  total: 0,
  // 其他模拟数据...
};

// 初始化模拟数据
const initMockData = () => {
  for(let i = 1; i <= 20; i++) {
    mockData.applyList.push({
      id: i,
      applyNo: `SQ${20240000 + i}`,
      applyType: i % 2 === 0 ? '1' : '2',
      applyUser: i % 3 + '',
      applyTime: Date.now() - i * 86400000,
      auditStatus: i % 4 + '',
      // 其他字段...
    });
  }
  mockData.total = 20;
};

// 组合式API
const router = useRouter();

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  applyNo: '',
  applyType: '',
  // 其他查询参数...
});

const form = reactive({
  id: null,
  applyNo: '',
  planNo: '',
  // 其他表单字段...
});

const detailList = ref([]);
const checkedIds = ref([]);
const showForm = ref(false);
const currentPage = ref(1);

// 计算属性
const single = computed(() => checkedIds.value.length !== 1);
const multiple = computed(() => !checkedIds.value.length);
const formTitle = computed(() => form.id ? '修改申请' : '新建申请');

// 生命周期
onMounted(() => {
  initMockData();
  loadData();
});

// 方法
const loadData = async () => {
  // 模拟接口调用
  await new Promise(resolve => setTimeout(resolve, 500));
  applyList.value = mockData.applyList.slice(
    (queryParams.pageNum - 1) * queryParams.pageSize,
    queryParams.pageNum * queryParams.pageSize
  );
  total.value = mockData.total;
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  loadData();
};

const handleAdd = () => {
  resetForm();
  showForm.value = true;
};

const handleUpdate = () => {
  const selected = mockData.applyList.find(item => item.id === checkedIds.value[0]);
  Object.assign(form, selected);
  showForm.value = true;
};

const saveForm = async () => {
  // 模拟保存
  await new Promise(resolve => setTimeout(resolve, 500));
  showForm.value = false;
  loadData();
};

// 状态样式
const getStatusTagType = (status) => {
  const types = ['', 'primary', 'warning', 'success', 'danger'];
  return types[status] || '';
};

// 格式化方法
const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleString();
};

// 其他方法...
</script>

<style lang="scss">
.app-container {
  padding: 16px;
  
  .action-btns {
    margin: 16px 0;
    display: flex;
    gap: 8px;
    
    van-button {
      flex: 1;
    }
  }

  .list-item {
    .item-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
      
      .item-no {
        font-weight: bold;
        color: #333;
      }
    }

    .item-content {
      display: flex;
      flex-direction: column;
      gap: 4px;
      font-size: 12px;
      color: #666;
    }
  }

  .form-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid #eee;
    
    .form-title {
      font-size: 18px;
      font-weight: bold;
      color: #4CAF50;
    }
  }

  .sub-table {
    margin: 16px;
    padding: 12px;
    background: #f8f8f8;
    border-radius: 8px;
    
    .sub-header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 12px;
    }
    
    .detail-item {
      margin-bottom: 12px;
      padding: 8px;
      background: white;
      border-radius: 6px;
    }
  }
}
</style>